//图片缓存
wx.images = {};

window.gameId = 9;
window.wx2g_openid = "";
window.wx2g_data = null
//nickName avatarUrl
window.wx2g_user = null;
window.wx2g_userinfo = null;
//启动参数
window.wx2g_startParams = null;
//系统信息
window.wx2g_systemInfo = null

wx.onShow(function (params) {
    window.wx2g_startParams = params;
    console.log("參數onshow：")
    console.log(params)

    if(window.wx2g_startParams){
        if (window.wx2g_show) {
            wx2g_show();
        }
    }
});

window.wx2g_getsystemInfo = function () {
    var res = wx.getSystemInfoSync();
    console.log(res);
	window.wx2g_systemInfo = res
    return res;
}

/**
 * public
 * 登录
 * @param back 登录回调函数
 */
window.wx2g_login = function (back) {
	wx2g_getsystemInfo()
    wx2g_2open({command: "loadImageCache"});
    wx.login({
        success: function (msg) {
            let testAppid = "wxe12a61c572e62c18";
            let testSecret = "d8ac14c2098e2a34dce5c704e2cd61e6";
            let appid = "wx80b17a4728b82ac8";
            let secret = "e6b74f19fae402ba9ba72d1586a2306f";
            let gameid = window.gameId;
            let url1 = "https://api.weixin.qq.com/sns/jscode2session?appid=" +
                appid + "&secret=" + secret + "&js_code=" + msg.code + "&grant_type=authorization_code"

            if(window.wx2g_startParams){
                let link_openid = window.wx2g_startParams.query.openid
                let link_gameid = window.wx2g_startParams.query.gameid
                if (link_openid) {
                    url1 = url1 + "&invite_openid=" + link_openid
                }
                if (link_gameid) {
                    gameid = link_gameid
                }
                url1 = url1 + "&game_id=" + gameid
            }

            let url = "https://cc.h5youxi.fun/login?" + encodeURI(url1);
            wx.request({
                url: url,
                success: function (data) {
                    let openid = data.data.openid;
                    window.wx2g_data = data.data
                    window.wx2g_openid = openid;
                    if (back) {
                        back();
                    }
                }
            });
        }
    });

    //显示顶部分享按钮
    wx.showShareMenu();
    wx.onShareAppMessage(function () {
        return wx2g_getTopShare();
    });

}


window.wx2g_showRewardVideo = function (back, fail,complete) {
    let videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-051c30d0e13a98b3'
    })
    videoAd.onError(err => {
        console.log(err)
		if (fail) fail(false);
      })
      
    videoAd.load()
        .then(() => videoAd.show())
        .catch(err => console.log(err.errMsg));
    videoAd.onClose(res => {
        // 用户点击了【关闭广告】按钮
        // 小于 2.1.0 的基础库版本，res 是一个 undefined
        if (res && res.isEnded || res === undefined) {
            console.log("rewardVideo play complete...")
            // 正常播放结束，可以下发游戏奖励
            if (back) back();
        }
        else {
            console.log("rewardVideo play quit...")
            // 播放中途退出，不下发游戏奖励
			if(fail) fail(true)
        }
        if (complete) complete();
    })
}

window.wx2g_hideBanner = function () {
    if (window.wx2g_bannerAd) {
        wx2g_bannerAd.destroy();
        wx2g_bannerAd = null;
    }
}

window.wx2g_showBannerBottom = function (adId = "adunit-38a6f5e65f6f7407") {
    wx2g_hideBanner();
    let bannerHeight = 80;
    let bannerWidth = 300;
    let bannerAd = wx.createBannerAd({
        adUnitId: adId,
        style: {
            left: (wx.getSystemInfoSync().windowWidth-bannerWidth)/2,
            top: wx.getSystemInfoSync().windowHeight-bannerHeight,
            width: bannerWidth,
        }
    });
    bannerAd.onError(() => {
        console.log("加载广告错误：");
        console.log(arguments);
        console.log("加载广告错误... end");
    });
    bannerAd.show();
    bannerAd.onLoad(() => {
        //bannerAd.style.width = wx.getSystemInfoSync().windowWidth;//bannerAd.style.realWidth * 30 / bannerAd.style.realHeight;
        bannerAd.style.top = wx.getSystemInfoSync().windowHeight - bannerAd.style.realHeight;// * bannerAd.style.width / bannerAd.style.realWidth;
    });
    window.wx2g_bannerAd = bannerAd;
}

/**
 * public
 * 初始化排行榜
 * @param names 排行榜名称数组，名称只能为字母组合
 */
window.wx2g_initRankList = function (names) {
    wx2g_2open({
        command: 'initRankList',
        names: names || ["rank"],
        openid: window.wx2g_openid
    });
}

window.wx2g_getRankGroupList = function (names) {
    if(window.wx2g_startParams&&window.wx2g_startParams.shareTicket){
        wx2g_2open({
            command: 'getRankGroupList',
            names: names || ["rank"],
            shareTicket:window.wx2g_startParams.shareTicket,
            openid: window.wx2g_openid
        });
    }
}

/**
 * public
 * 重置排行榜页数
 * @param name
 * @param pageCount 一页显示的个数
 */
window.wx2g_resetRankPage = function (name = "rank", pageCount = 5) {
    wx2g_2open({
        command: "resetRankPage",
        name: name,
        pageCount: pageCount
    });
}
window.wx2g_loadImageCache = function (urls) {
    wx2g_2open({
        command: "loadImageCache",
        urls: urls
    });
}
/**
 * 排行榜向左翻页
 * @param name
 */
window.wx2g_rankPageLeft = function (name = "rank") {
    wx2g_2open({
        command: "rankPageLeft",
        name: name
    });
}

/**
 * 排行榜向右翻页
 * @param name
 */
window.wx2g_rankPageRight = function (name = "rank") {
    wx2g_2open({
        command: "rankPageRight",
        name: name
    });
}

/**
 * public
 * 绘制排行榜
 * @param style 排行榜样式，默认为 1
 */
window.wx2g_drawRank = function (name = "rank", style = 1) {
    let sharedCanvas = wx.getOpenDataContext().canvas;
    if (style == 1) {
        sharedCanvas.width = 550;
        sharedCanvas.height = 800;
    } else if (style == 2) {
        sharedCanvas.width = 660;
        sharedCanvas.height = 800;
    }
    wx2g_2open({
        command: "drawRank",
        name: name,
        style: style
    });
    return sharedCanvas;
}

/**
 * public
 * 上传排行榜分数
 * @param score 分数
 * @param name
 */
window.wx2g_uploadRank = function (score, name = "rank") {
    wx2g_2open({
        command: "uploadRank",
        name: name,
        score: score
    });
}

/**
 * 绘制最佳分数
 */
window.wx2g_drawBestScore = function (rank, width, height, size, font, color) {
    let sharedCanvas = wx.getOpenDataContext().canvas;
    sharedCanvas.width = width;
    sharedCanvas.height = height;
    wx2g_2open({
        command: "drawBestScore",
        name: rank,
        size: size,
        font: font,
        color: color
    });
    return sharedCanvas;
}

/**
 * 绘制当前排名
 */
window.wx2g_drawRankIndex = function (rank, width, height, size, font, color) {
    let sharedCanvas = wx.getOpenDataContext().canvas;
    sharedCanvas.width = width;
    sharedCanvas.height = height;
    wx2g_2open({
        command: "drawRankIndex",
        name: rank,
        size: size,
        font: font,
        color: color
    });
    return sharedCanvas;
}

/**
 * 绘制排行榜下一名好友
 */
window.wx2g_drawNextRank = function (score = 0, style = 1, name = "rank") {
    let sharedCanvas = wx.getOpenDataContext().canvas;
    if (style == 1) {
        sharedCanvas.width = 200;
        sharedCanvas.height = 70;
    } else if (style == 1000) {
        sharedCanvas.width = 150;
        sharedCanvas.height = 191;
    } else if (style == 3) {
        sharedCanvas.width = 113;
        sharedCanvas.height = 170;
    } else if (style == 4) {
        sharedCanvas.width = 168 + 30;
        sharedCanvas.height = 99 + 30;
    }
    wx2g_2open({
        command: "drawNextRank",
        name: name,
        style: style,
        score: score
    });
    return sharedCanvas;
}
//绘制超越用户
window.wx2g_drawOverStep = function (score = 1, style = 1) {
    let sharedCanvas = wx.getOpenDataContext().canvas;
    if (style == 2) {
        sharedCanvas.width = 480;
        sharedCanvas.height = 50;
    }
    wx2g_2open({
        command: "drawOverStep",
        style: style,
        score: score
    });
    return sharedCanvas;
}
/**
 * 绘制比你高的玩家
 * @param score
 * @param name
 * @param style
 */
window.wx2g_drawNextUser = function(score = 0, style = 1) {
    let sharedCanvas = wx.getOpenDataContext().canvas;
    if(style == 1) {
        sharedCanvas.width = 500;
        sharedCanvas.height = 100;
    }else{
        sharedCanvas.width = 500;
        sharedCanvas.height = 100;
    }
    wx2g_2open({
        command:"drawNextUser",
        style:style,
        score:score
    });
    return sharedCanvas;
}
/**
 * 绘制小排行榜
 */
window.wx2g_drawMiniRank = function (score = 0, name = "rank", style = 1) {
    let sharedCanvas = wx.getOpenDataContext().canvas;
    if (style == 1) {
        sharedCanvas.width = 480;
        sharedCanvas.height = 190;
    } else if (style == 2) {
        sharedCanvas.width = 480;
        sharedCanvas.height = 190;
    }
    wx2g_2open({
        command: "drawMiniRank",
        name: name,
        style: style,
        score: score
    });
    return sharedCanvas;
}

/**
 * public
 * @param msg 分享的文字
 * @param url 图片地址
 * @param success
 * @param fail
 */
window.wx2g_share = function (shareObj) {
    wx.updateShareMenu({
        withShareTicket: true,
        success: function () {
            console.log("[update share menu]");
            console.log(arguments);
        },
        success: function () {
            console.log("updateShareMenu success");
            console.log(arguments);
        }
    });
    setTimeout(function () {
        wx.shareAppMessage(shareObj);
    });
}

/**
 * private
 * 发送数据给开放域
 * @param data
 */
window.wx2g_2open = function (data) {
    let openDataContext = wx.getOpenDataContext();
    openDataContext.postMessage(data);
}

window.wx2g_getUserInfo = function (back) {
    console.log("wx2g_getUserInfo...")
    let btnW = 145;
    let btnH = 42;
    let button = wx.createUserInfoButton({
        type: 'image',
        image: "https://img.h5youxi.fun/login2.png",
        // text: '获取用户信息',
        style: {
            left: (wx.getSystemInfoSync().windowWidth - btnW) / 2,
            top: wx.getSystemInfoSync().windowHeight/1.5 - btnH,
            width: btnW,
            height: btnH,
            lineHeight: 40,
            backgroundColor: '#ff0000',
            color: '#ffffff',
            textAlign: 'center',
            fontSize: 16,
            borderRadius: 4
        }
    })
	
	let hassuc = false
	let failshowbtn = false
    let getRealUserInfo = function () {
        wx.getUserInfo({
            openIdList: [],
            success: result => {
                window.wx2g_userinfo = result
                //	console.log(result)
                if (back)
                    back(result.userInfo)
				hassuc = true
            },
            fail(err) {
                button.show();
                console.log(err, "get UserInfo fail................................")
				failshowbtn = true
            },
			complete(){
				if (hassuc==false&&failshowbtn==false&&back)
                    back()
				hassuc = false
			}
        });
    }
    button.hide();
    getRealUserInfo();

    button.onTap((res) => {
        button.hide();
        getRealUserInfo();
        //console.log(res)
    })
}

window.wx2g_getUserInfoHide = function (back) {
	let getRealUserInfo2 = function () {
		wx.getUserInfo({
			openIdList: [],
			success: result => {
				window.wx2g_userinfo = result
				if (back)
					back(result.userInfo)
			},
			fail(err) {
				console.log(err, "get UserInfo fail................................")
			}
		});
    }
    getRealUserInfo2();
}


/**
 * public
 * 小震動
 */
window.wx2g_shakeSmall = function () {
    wx.vibrateShort();
}

/**
 * public
 * 打震動
 */
window.wx2g_shakeBig = function () {
    wx.vibrateLong();
}

//支付
window.wx2g_pay= function(num ,back){	
	console.log("支付数目")
	console.log(num)
	wx.requestMidasPayment({
	  mode: 'game',
	  env:0,
	  offerId: '1450019146',
	  buyQuantity: num,
	  platform: "android",
	  zoneId: 1,
	  success() {
		console.log("支付成功")
		if(back)	back()
	  },
	  fail({errMsg, errCode}) {  
		console.log("支付失败")
		console.log(errMsg, errCode)
	  }
	})	
}
	
	
///复制
window.wx2g_copyclip=function(str){
	wx.setClipboardData({
	  data: str,
	  success(res) {
		wx.getClipboardData({
		  success(res) {
			console.log(res.data) // data
		  }
		})
	  }
	})
}
	
	